<template>
  <div class="app-container">
    <!-- 第一行图表容器 -->
    <div class="chart-container">
      <!-- 饼图 -->
      <div class="chart-item">
        <template v-if="eatDataSet.length > 0">
          <e-charts :option="eatChartOption" autoresize />
        </template>
        <template v-else>
          <div class="empty-placeholder">
            <span class="text">暂无今日进食营养摄入数据</span>
          </div>
        </template>
      </div>

      <!-- 堆叠柱状图 -->
      <div class="chart-item">
        <template v-if="eatNrvDataSet.length > 0">
          <e-charts :option="eatChartNrvOption" autoresize />
        </template>
        <template v-else>
          <div class="empty-placeholder">
            <span class="text">暂无今日营养素参考数据</span>
          </div>
        </template>
      </div>
    </div>

    <!-- 第二行图表容器 -->
    <div class="chart-container">
      <!-- 饮水摄入饼图 -->
      <div class="chart-item">
        <template v-if="drinkDataSet.length > 0">
          <e-charts :option="drinkChartOption" autoresize />
        </template>
        <template v-else>
          <div class="empty-placeholder">
            <span class="text">暂无今日饮水摄入数据</span>
          </div>
        </template>
      </div>

      <!-- 折线图 -->
      <div class="chart-item">
        <template v-if="eatDayDataSet.length > 0">
          <e-charts :option="lineChartOption" autoresize />
        </template>
        <template v-else>
          <div class="empty-placeholder">
            <span class="text">暂无近七日营养摄入数据</span>
          </div>
        </template>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watchEffect } from 'vue'
import { listEatShowData, listEatShowDataNrv, listDrinkShowData, listEatShowDataWithDay } from "@/api/manage/showdata"
import { notNullish } from '@vueuse/core'

// 定义响应式数据
const eatDataSet = ref([])
const eatNrvDataSet = ref([])
const drinkDataSet = ref([])
const eatDayDataSet = ref([])
const eatChartOption = ref({})
const eatChartNrvOption = ref({})
const drinkChartOption = ref({})
const lineChartOption = ref({}) // 新增折线图配置

// 获取今日摄入营养成分数据
function getEatShowData () {
  listEatShowData().then(response => {
    eatDataSet.value = response.data
  })
}

// 获取今日饮水摄入营养成分数据
function getDrinkShowData () {
  listDrinkShowData().then(response => {
    drinkDataSet.value = response.data
  })
}

// 获取今日摄入营养成分在标准值的占比数据
function getEatShowDataNrv () {
  listEatShowDataNrv().then(response => {
    eatNrvDataSet.value = response.data
  })
}

// 获取近7日进食摄入营养成分
function getEatShowDataWithDay () {
  listEatShowDataWithDay().then(response => {
    eatDayDataSet.value = response.data
  })
}

// 通用图表配置
function getCommonChartOptions (title) {
  return {
    title: {
      text: title,
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      bottom: 10,
      left: 'center'
    },
    grid: {
      left: 100,
      right: 100,
      top: 50,
      bottom: 50
    }
  }
}

// 监听 eatDataSet 和 eatNrvDataSet 的变化，更新图表配置
watchEffect(() => {
  if (eatDataSet.value.length > 0) {
    // 更新饼图配置
    const pieSeriesData = eatDataSet.value.map(item => ({
      value: item.values[0],
      name: item.name,
      unit: item.unit
    }))

    eatChartOption.value = {
      ...getCommonChartOptions('每日进食营养摄入'),
      tooltip: {
        trigger: 'item',
        formatter: (params) => {
          // 添加颜色小圆点
          return `
            <div style="display: flex; align-items: center;">
              <span style="display: inline-block; width: 10px; height: 10px; border-radius: 50%; background: ${params.color}; margin-right: 5px;"></span>
              <span>摄入：${params.value} ${params.data.unit}</br>占比：${params.percent}%</span>
            </div>
          `
        }
      },
      series: [
        {
          name: '营养摄入',
          type: 'pie',
          radius: '50%',
          center: ['50%', '50%'],
          data: pieSeriesData,
          label: {
            formatter: (params) => `${params.name}（${params.value} ${params.data.unit}）`,
            position: 'outside',
            alignTo: 'labelLine',
            bleedMargin: 5,
            distance: 10
          },
          labelLine: {
            show: true
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
  }

  if (eatNrvDataSet.value.length > 0) {
    // 更新堆叠柱状图配置
    const xAxisData = eatNrvDataSet.value.map(item => item.dietName)
    const nutritionNames = [...new Set(eatNrvDataSet.value.flatMap(item => item.nutrition.map(n => n.name)))]

    const barSeries = nutritionNames.map(name => ({
      name: name,
      type: 'bar',
      stack: 'total',
      barWidth: '60%',
      label: {
        show: true,
        formatter: (params) => {
          // ${params.seriesName}\n
          return `${params.value}%`
        }
      },
      data: eatNrvDataSet.value.map(item => {
        const nutrition = item.nutrition.find(n => n.name === name)
        return nutrition ? nutrition.refValue : null
      })
    }))

    eatChartNrvOption.value = {
      ...getCommonChartOptions('每日进食营养摄入营养素参考'),
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: function (params) {
          // 检查 params 是否为 undefined 或 null
          if (!params || params.length === 0) return ''

          let tooltipContent = ''
          params.forEach(param => {
            // 检查 param.value 是否为 undefined 或 null
            if (param.value != null) {
              // 添加颜色小圆点
              tooltipContent += `
                <div style="display: flex; align-items: center;">
                  <span style="display: inline-block; width: 10px; height: 10px; border-radius: 50%; background: ${param.color}; margin-right: 5px;"></span>
                  <span>${param.seriesName}：${param.value}%</span>
                </div>
              `
            }
          })
          return tooltipContent
        }
      },
      xAxis: {
        type: 'category',
        data: xAxisData
      },
      yAxis: {
        type: 'value',
        name: '营养素参考值'
      },
      series: barSeries
    }
  }

  if (drinkDataSet.value.length > 0) {
    // 更新饮水摄入饼图配置
    const drinkPieSeriesData = drinkDataSet.value.map(item => ({
      value: item.refValue,
      name: item.name,
      unit: item.unit || 'ml' // 如果 unit 为 null，默认使用 'ml'
    }))

    drinkChartOption.value = {
      ...getCommonChartOptions('每日饮水营养摄入'),
      tooltip: {
        trigger: 'item',
        formatter: (params) => {
          // 添加颜色小圆点
          return `
            <div style="display: flex; align-items: center;">
              <span style="display: inline-block; width: 10px; height: 10px; border-radius: 50%; background: ${params.color}; margin-right: 5px;"></span>
              <span>摄入：${params.value} ${params.data.unit}</br>占比：${params.percent}%</span>
            </div>
          `
        }
      },
      series: [
        {
          name: '饮水摄入',
          type: 'pie',
          radius: '50%',
          center: ['50%', '50%'],
          data: drinkPieSeriesData,
          label: {
            formatter: (params) => `${params.name}（${params.value} ${params.data.unit}）`,
            position: 'outside',
            alignTo: 'labelLine',
            bleedMargin: 5,
            distance: 10
          },
          labelLine: {
            show: true
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
  }

  // 处理折线图数据
  if (eatDayDataSet.value.length > 0) {
    // 获取所有营养成分名称
    const nutritionNames = [...new Set(eatDayDataSet.value.flatMap(item => item.nutrition.map(n => n.name)))]

    // 获取所有日期并排序
    const dietTimes = [...new Set(eatDayDataSet.value.map(item => item.dietTime))].sort()

    // 构造折线图数据
    const lineSeries = nutritionNames.map(name => {
      const unit = eatDayDataSet.value
        .flatMap(item => item.nutrition)
        .find(n => n.name === name)?.unit || ''

      return {
        name: name,
        type: 'line',
        data: dietTimes.map(time => {
          const item = eatDayDataSet.value.find(item => item.dietTime === time)
          const nutrition = item?.nutrition.find(n => n.name === name)
          return nutrition ? nutrition.refValue : 0
        }),
        unit: unit // 保留 unit 信息
      }
    })

    // 折线图配置
    lineChartOption.value = {
      ...getCommonChartOptions('近7日营养摄入趋势'),
      tooltip: {
        trigger: 'axis',
        formatter: (params) => {
          let tooltipContent = `<div style="margin-bottom: 5px;">${params[0].axisValue}</div>`
          params.forEach(param => {
            // 如果值为 0，不显示该成分
            if (param.value !== 0) {
              // 通过 param.seriesName 查找对应的 unit
              const series = lineSeries.find(s => s.name === param.seriesName)
              const unit = series ? series.unit : ''
              tooltipContent += `
              <div style="display: flex; align-items: center;">
                <span style="display: inline-block; width: 10px; height: 10px; border-radius: 50%; background: ${param.color}; margin-right: 5px;"></span>
                <span>${param.seriesName}：${param.value} ${unit}</span>
              </div>
            `
            }
          })
          return tooltipContent
        }
      },
      xAxis: {
        type: 'category',
        data: dietTimes.map(time => new Date(time).toLocaleDateString()),
        axisLabel: {
          rotate: 45 // 如果日期过长，可以旋转标签
        }
      },
      yAxis: {
        type: 'value',
        name: '摄入量'
      },
      legend: {
        top: 30, // 将 legend 移到上方
        left: 'center', // 水平居中
        icon: 'circle', // 设置图例图标为圆形
        itemWidth: 10, // 图例图标宽度
        itemHeight: 10, // 图例图标高度
        itemGap: 20, // 图例之间的间距
        textStyle: {
          fontSize: 12 // 图例文字大小
        }
      },
      series: lineSeries
    }
  }
})

// 初始化时调用 API 获取数据
getEatShowData()
getEatShowDataNrv()
getDrinkShowData()
getEatShowDataWithDay()
</script>

<style scoped>
.app-container {
  display: flex;
  flex-direction: column;
  gap: 20px; /* 行与行之间的间距 */
  height: 100vh; /* 让容器占满整个页面高度 */
  padding: 20px; /* 增加内边距 */
  box-sizing: border-box; /* 防止 padding 影响布局 */
}

.chart-container {
  display: flex;
  justify-content: space-between;
  gap: 20px; /* 图表之间的间距 */
  height: 50%; /* 每行占一半高度 */
}

.chart-item {
  flex: 1;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
}

.empty-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 16px;
}

.empty-placeholder .icon {
  font-size: 32px;
  margin-bottom: 10px;
}

.empty-placeholder .text {
  text-align: center;
}
</style>